//导入express
var express = require('express');
var router = express.Router();
//导入 jwt
const jwt = require('jsonwebtoken');
//导入配置文件
const {secret} = require('../config/config')
//导入模型文档           用户的模型文档
const UserModel = require('../models/UserModel');
const orderModel = require('../models/orderModel')
const md5 = require('md5');
//导入中间件(验证token的中间件)
let checkTokenMiddleware = require('../middlewares/checkTokenMiddleware');

//查询所有用户
router.get('/alluser',(req,res)=>{
  UserModel.find()
  .then(data =>{
    res.json({
      statuscode:'000',
      msg:'查询所有用户数据成功',
      data:data
    })
  })
  .catch(err =>{
    throw err
  })
})


//修改订单的状态
router.patch('/changetype', async (req, res) => {
  let {username,uuid,type} = req.body
  UserModel.findOneAndUpdate(
    { username: username, "allorder.uuid": uuid },
    { $set: { "allorder.$.type": type } },
    { new: true })
    .then(data =>{
      console.log("更新成功！");
      // 处理成功
      res.json({
        statuscode:"000",
        msg:"更新订单状态成功",
        data:data
      })
    })
    .catch(err =>{throw err})
});


//删除已完成的用户订单/取消订单
router.delete('/removeorder',(req,res)=>{
  let {username} = req.body
  let {uuid} =req.body
  if(uuid && username){
    UserModel.findOneAndUpdate({username:username},
      { $pull: { allorder: { uuid: uuid } } }, 
      { new: true })
    .then(data =>{
      res.json({
        statuscode:"000",
        msg:"取消/删除订单成功",
        data:data
      })
    })
    .catch(err =>{
      throw err
    })
  }else{
    res.json({
      statuscode:"000",
      msg:"username为"+username+",uuid为"+uuid
    })
  }
  
})


//获取所有的服务项目
router.get('/getorder',(req,res)=>{
  orderModel.find()
  .then(data =>{
    res.json({
      statuscode:"000",
      msg:"查询订单完成",
      data:data
    })
  })
  .catch(err =>{
    throw err
  })
})


//管理员新增订单
router.post('/neworder', (req, res) => {
  const { title, img, price, times, lastprice ,introduce} = req.body;

  const newOrder = new orderModel({
    title,
    img,
    price,
    times,
    introduce,
    lastprice
  });

  newOrder.save()
    .then(savedOrder => {
      res.json({
        statuscode: "000",
        msg: "新增订单成功",
        data: savedOrder
      });
    })
    .catch(err => {
      console.error('Failed to save order', err);
      res.json({
        statuscode: "000",
        msg: "新增订单失败",
        err: err
      });
    });
});


module.exports = router;
